package com.qf.blog.controller;

import com.alibaba.fastjson.JSON;
import com.qf.blog.entity.User;
import com.qf.blog.exception.BlogException;
import com.qf.blog.service.IUserService;
import com.qf.blog.utils.Result;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@RestController
public class UploadController {

    @Value("${blog.qiniu.host}")
    private String host;

    @Value("${blog.qiniu.ak}")
    private String ak;

    @Value("${blog.qiniu.sk}")
    private String sk;

    @Value("${blog.qiniu.bucket}")
    private String bucket;

    @Autowired
    private UploadManager uploadManager;

    @Autowired
    private IUserService userService;

    @PostMapping("/uploadFile")
    public Result uploadFile(MultipartFile file, HttpSession session) throws Exception {

        User loginUser = (User) session.getAttribute("loginUser");
        if (loginUser == null) {
            throw new BlogException(1002, "请先登录");
        }
        String originalFilename = file.getOriginalFilename();

        // 实现认证 返回一个token
        Auth auth = Auth.create(ak, sk);
        String upToken = auth.uploadToken(bucket);
        try {
            // 把用户选择的头像上传到七牛云服务器
            Response response = uploadManager.put(file.getBytes(), originalFilename, upToken);
            //解析上传成功的结果
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            // 文件名称前面拼接上域名得到文件的绝对路径
            String fileUrl = host + defaultPutRet.key;

            // 更新用户的头像
            Integer status = userService.updateUserHeader(loginUser.getId(),fileUrl);

        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return Result.ok();
    }
}
